package com.mdsi.secretary;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mdsi.models.ConnectionManager;
import com.mdsi.models.Student;

/**
 * Servlet implementation class SecretaryServlet
 */
@WebServlet("/User/Secretary")
public class SecretaryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SecretaryServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    
    
    
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			
			Connection conn = ConnectionManager.getConnection() ;
			PreparedStatement st = null ;
			ResultSet result = null ;
			String sqlRequest = "" ;
			
				// La liste des étudiants
					sqlRequest = "SELECT DISTINCT S.ID_STUDENT, S.NUM, S.FIRSTNAME, S.LASTNAME, S.EMAIL, S.BIRTHDATE, S.NATIONALITY "
						+ "FROM student S"
						+ "ORDER BY S.FIRSTNAME, S.LASTNAME" ;
							
			
		
					
					st = conn.prepareStatement(sqlRequest) ;
					result = st.executeQuery() ;
					ArrayList <Student> students = new ArrayList <Student> () ;
					while (result.next()) {
						Calendar birthdate = GregorianCalendar.getInstance() ;
						birthdate.setTime(result.getDate("BIRTHDATE")) ;
						students.add(new Student(
							result.getLong("ID_STUDENT"), 
							result.getString("FIRSTNAME"), 
							result.getString("LASTNAME"),
							result.getString("EMAIL"), 
							result.getLong("NUM"), 
							birthdate, 
							result.getString("NATIONALITY"))) ;
					}
					
					conn.close () ;
					getServletContext().setAttribute("students", students) ;
				} 
				catch (SQLException e) {
					e.printStackTrace();
				}
		
		
		this.getServletContext().getRequestDispatcher("/WEB-INF/secretary/secretary.jsp").forward(request, response);		
	}

}
